<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    <meta name="viewport"
          content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"/>
    <title>群聊</title>
    <link rel="stylesheet" type="text/css" href="/js/plugins/chat/chat.css"/>
    <script src="/js/jquery/jquery.min.js"></script>
    <script src="/js/plugins/chat/flexible.js"></script>
    <script src="/js/common.js"></script>
    <script src="/js/plugins/jrender/jrender.min.js"></script>
    <link rel="stylesheet" href="/js/plugins/dialog2/dialog.css">
    <script src="/js/plugins/dialog2/dialog.min.js"></script>
    <script src="/js/common.js"></script>
    <script src="../js/checkLogin.js"></script>

    <script>
        $(function () {
            var ws;
            var tt;
            var times = 0;
            var url = "ws://127.0.0.1:8088/websocketDemo/" + user.id;
            var params = getParams();
            function createWebSocket() {
                try {
                    if('WebSocket' in window) {
                        console.log("此浏览器支持websocket");
                        ws = new WebSocket(url);
                    } else if('MozWebSocket' in window) {
                        alert("此浏览器只支持MozWebSocket");
                    } else {
                        alert("此浏览器只支持SockJS");
                    }
                    init();
                } catch(e) {
                    reconnect(url);
                }
            }

            function init() {

                var receiverInfo;
                $.get(baseUrl + "/users/" + params.receiverId, function (data) {
                    receiverInfo = data.data;
                });

                ws.onclose = function () {
                    $("#tou").html("与服务器断开了链接!")
                    console.log('链接关闭');
                    reconnect(url);
                };
                ws.onerror = function() {
                    console.log('发生异常了');
                    reconnect(url);
                };
                ws.onopen = function () {
                    $("#tou").html("链接服务器成功!")
                    //心跳检测重置
                    heartCheck.start();
                };
                ws.onmessage = function (event) {

                    if (event.data != "__PONG"){
                        send(receiverInfo.headImgUrl, event.data, CurentTime(new Date()));
                        end();
                    }
                    //拿到任何消息都说明当前连接是正常的,重置我们的心跳.
                    heartCheck.start();
                }
            }

            var lockReconnect = false;//避免重复连接
            function reconnect(url) {
                if(lockReconnect) {
                    return;
                };
                if (times++ >=2){
                    $("#tou").html("与服务器链接失败!")
                    return;
                };
                lockReconnect = true;
                //没连接上会一直重连，设置延迟避免请求过多
                tt && clearTimeout(tt);
                tt = setTimeout(function () {
                    createWebSocket(url);
                    lockReconnect = false;
                }, 4000);
            }
            window.onbeforeunload = function () {
                ws.close();
            };

            var heartCheck = {
                timeout: 3000,
                timeoutObj: null,
                serverTimeoutObj: null,
                start: function(){
                    console.log('start');
                    var self = this;
                    this.timeoutObj && clearTimeout(this.timeoutObj);
                    this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
                    this.timeoutObj = setTimeout(function(){
                        //这里发送一个心跳，后端收到后，返回一个心跳消息，
                        //onmessage拿到返回的心跳就说明连接正常
                        ws.send("__PING");
                        self.serverTimeoutObj = setTimeout(function() {
                            ws.close();
                            // createWebSocket();
                        }, self.timeout);

                    }, this.timeout)
                }
            };
            console.log(123);


            createWebSocket()
            $('#sendBtn').bind('click', function () {
                sendSocket();
            });



            function sendSocket() {
                if (ws != null) {
                    var message = $("input[name='message']").val();
                    show(user.headImgUrl, message, CurentTime(new Date()));
                    end();
                    $.get("http://127.0.0.1:8088/messages/groups/" + params.receiverId + "?message=" + message,{userId: user.id, chatId:params.receiverId}, function (data) {
                        if(!data.success){
                            console.log(data);
                            $(document).dialog({
                                overlayClose: true,
                                content: data.errorMsg,
                            });
                        }
                    });
                    //websocket.send(message);
                } else {
                    alert('未与服务器链接.');
                }
            }
        });
    </script>
</head>

<body>
<header class="header">
    <a class="back" href="javascript:history.go(-1);"></a>
    <h5 class="tit receiverName"></h5>
    <div class="right receiverData">资料</div>
</header>

<div class="message">
    <!--<div class="send">
        <div class="time">05/22 06:30</div>
        <div class="msg">
            <img id="sendImg" width="40px" alt="" />
            <p><i class="msg_input"></i>你好在不在呀，妹子！</p>
        </div>
    </div>-->

    <!--<div class="show">
        <div class="time">05/22 06:30</div>
        <div class="msg">
            <img id="receiverImg" width="40px" alt="" />
            <p><i class="msg_input"></i>你好你好你好</p>
        </div>
    </div>-->
</div>
<div class="footer">
    <img src="/img/xiaolian.png"/>
    <input type="text" name="message">
    <p id="sendBtn">发送</p>
</div>
<script src="/js/group.js"></script>



</body>
</html>